package com.example.myfirst.controller;

import com.example.myfirst.entity.Shops;
import com.example.myfirst.service.ShopsService;
import com.example.myfirst.utils.AliOSSUtils;
import com.example.myfirst.vo.ResultVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("shops")
@CrossOrigin
public class ShopsController {
    @Autowired
    private ShopsService shopsService;

    @ApiOperation("查询所有店铺")
    @GetMapping
    public ResultVo getAllShops() {
        List<Shops> shopsList = shopsService.queryAllShops();
        return new ResultVo(shopsList);
    }

    @ApiOperation("添加店铺")
    @PostMapping
    public ResultVo addShop(@RequestBody Shops shops) {
        boolean flag = shopsService.addShop(shops);
        ResultVo vo = new ResultVo<>();
        if (flag) {
            vo.setMessage("添加店铺成功");
            vo.setSuccess(true);
        } else {
            vo.setMessage("添加店铺失败~");
            vo.setSuccess(false);
        }
        vo.setCode(200);
        return vo;
    }

    @ApiOperation("上传图片")
    @PostMapping("/upload")
    public ResultVo upload(MultipartFile image) throws IOException {
        log.info("文件上传,文件名:{}", image.getOriginalFilename());
        // 调用阿里云上传文件
        String url = AliOSSUtils.upload(image);
        log.info("文件上传完成,文件url:{}", url);
        return new ResultVo(url);
    }

    @ApiOperation("根据店铺id删除")
    @DeleteMapping("/{id}")
    public ResultVo delShop(@PathVariable Integer id) {
        boolean flag = shopsService.delShopById(id);
        ResultVo vo = new ResultVo<>();
        if (flag) {
            vo.setMessage("删除店铺成功");
            vo.setSuccess(true);
        } else {
            vo.setMessage("删除店铺失败~");
            vo.setSuccess(false);
        }
        vo.setCode(200);
        return vo;
    }

    @ApiOperation("根据id获取店铺里面所有的商品信息")
    @GetMapping("/search")
    public ResultVo getShop(Integer shop_id) {
        List<Shops> shop = shopsService.findShopById(shop_id);
        return new ResultVo(shop);
    }

    // 同时根据店铺id获取所属店铺所有商品
    @ApiOperation("根据店铺id修改")
    @PutMapping("/{id}")
    public ResultVo updateShop(@RequestBody Shops shops, @PathVariable Integer id) {
        Boolean flag = shopsService.updateShopById(shops, id);
        ResultVo vo = new ResultVo<>();
        if (flag) {
            vo.setMessage("更新店铺成功");
            vo.setSuccess(true);
        } else {
            vo.setMessage("更新店铺失败~");
            vo.setSuccess(false);
        }
        vo.setCode(200);
        return vo;
    }
}
